package com.jwork.progress.service.job;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.spring.util.BeanUtils;
import com.jwork.progress.params.CommonResponse;
import com.jwork.progress.pojo.dto.job.JobCreateDTO;
import lombok.RequiredArgsConstructor;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
@RequiredArgsConstructor
public class JobService {
    private final Logger logger = LoggerFactory.getLogger(JobService.class);
    private final Scheduler scheduler;

    public CommonResponse createJob(JobCreateDTO dto) {
        JobKey jobKey = new JobKey(dto.getJobName(), dto.getGroup());
        Map<String, Object> paramsMap = BeanUtil.beanToMap(dto);

        try {
            JobDetail job =
                    JobBuilder.newJob(SampleJob.class).withIdentity(jobKey).usingJobData(new JobDataMap(paramsMap)).build();
            Trigger trigger = TriggerBuilder.newTrigger()
                    .withIdentity(dto.getJobName() + "_Trigger", dto.getGroup())
                    .withSchedule(CronScheduleBuilder.cronSchedule(dto.getCron())).build();
            if (scheduler.checkExists(jobKey)) {
                scheduler.rescheduleJob(trigger.getKey(), trigger);
            } else {
                scheduler.scheduleJob(job, trigger);
            }
            return CommonResponse.success("创建成功！");
        } catch (SchedulerException e) {
            logger.error("创建异常：{}", e.getMessage());
            throw new RuntimeException(e);
        }
    }

    public CommonResponse pauseJob(String group, String name) {
        try {
            scheduler.pauseJob(new JobKey(name, group));
            return CommonResponse.success("暂停成功！");
        } catch (SchedulerException e) {
            logger.error("暂停任务异常：{}", e.getMessage());
            throw new RuntimeException(e);
        }
    }

    public CommonResponse resumeJob(String group, String name) {
        try {
            scheduler.resumeJob(new JobKey(name, group));
            return CommonResponse.success("恢复成功！");
        } catch (SchedulerException e) {
            logger.error("恢复任务异常：{}", e.getMessage());
            throw new RuntimeException(e);
        }
    }

    public CommonResponse deleteJob(String group, String name) {
        try {
            scheduler.deleteJob(new JobKey(name, group));
            return CommonResponse.success("删除成功！");
        } catch (SchedulerException e) {
            logger.error("删除任务异常：{}", e.getMessage());
            throw new RuntimeException(e);
        }
    }
}
